package com.lwl.mini.transaction;

import com.lwl.mini.exceptions.ExceptionFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author lwl
 * @create 2022/4/14 14:15
 */
public class DefaultTransaction implements Transaction {
    private DataSource dataSource;
    private Connection connection;
    private final boolean autoCommit;
    private final TransactionIsolationLevel level;

    public DefaultTransaction(DataSource dataSource, boolean autoCommit, TransactionIsolationLevel level) {
        this.dataSource = dataSource;
        this.autoCommit = autoCommit;
        try {
            this.connection = dataSource.getConnection();
        } catch (SQLException e) {
            throw ExceptionFactory.wrapException("从数据源中获取连接出错: " + e, e);
        }
        this.level = level;
    }

    @Override
    public Connection getConnection() {
        try {
            //手动提交或自动提交
            connection.setAutoCommit(autoCommit);
            if (level != null) {
                //传入隔离级别
                connection.setTransactionIsolation(level.getLevel());
            }
        } catch (SQLException e) {
            throw ExceptionFactory.wrapException("传入connection隔离级别时出错: " + e, e);
        }
        return connection;
    }

    @Override
    public void commit() throws SQLException {
        if (connection != null) {
            connection.commit();
        }
    }

    @Override
    public void close() throws SQLException {
        if (connection != null) {
            connection.close();
        }
    }
}
